//https://autumnfish.cn
axios.defaults.baseURL = 'http://82.157.247.15';

const vue = new Vue({
    el: "#app",
    data: {
        // 搜索关键字
        query: '',
        // 歌曲列表
        musicList: [],
        // 歌曲url
        musicUrl: '',
        // 是否正在播放
        isPlay: false,
        // 歌曲封面地址
        coverUrl: '',
        //储存当前播放歌曲的索引
        currentIndex: -1,
        //是否展示专辑封面
        isAlbumDisplay: false,
        //播放器音量
        volume: 100,
        //当前已经播放的时间
        currentTime: 0,
        //音乐总时长
        totalTime: 0,
        //定时器
        timer: null,

    },
    methods: {
        // 搜索歌曲
        searchMusic() {
            if (this.query === 0) {
                return
            }
            axios.get('/search?keywords=' + this.query).then(response => {
                // 保存内容
                this.musicList = response.data.result.songs;
            })
            // 清空搜索
            this.query = ''
        },
        setPlayerSrcAndCover(musicId) {
            //判断当前播放索引是否在musicList的大小范围之内
            if (this.currentIndex < 0 || this.currentIndex >= this.musicList.length)
                return;
            if (typeof musicId === "undefined")
                musicId = this.musicList[this.currentIndex].id;
            //将音乐播放标志置位true，表示正在播放音乐
            this.isPlay = true
            // 获取歌曲url
            axios.get('/song/url?id=' + musicId).then(response => {
                // 保存歌曲url地址
                this.musicUrl = response.data.data[0].url;
            })
            // this.musicUrl="http://music.163.com/song/media/outer/url?id=" + musicId +".mp3"
            // 获取歌曲封面
            axios.get("/?type=detail&id=" + musicId).then(response => {
                // 设置封面
                this.coverUrl = response.data.songs[0].al.picUrl
                this.$refs.bg.style.backgroundImage = `url(${this.coverUrl})`;
            })
        },
        // 播放歌曲
        playMusic(index) {
            if (index === this.currentIndex) {
                this.playOrPause()
                return;
            }

            //设置当前播放歌曲索引
            this.currentIndex = index;
            //设置音乐播放和封面图片
            this.setPlayerSrcAndCover()
        },
        // audio的play事件
        playOrPause() {
            //判断musicList是否有数据，防止无效播放
            if (this.musicList.length <= 0)
                return;
            //切换播放状态
            this.isPlay = !this.isPlay;
            if (!this.isPlay) {
                this.$refs.myAudio.pause();
                return;
            }
            //判断播放器是否已经播放过歌曲
            if (this.currentIndex > -1)
                this.$refs.myAudio.play()
            else {
                this.currentIndex = 0
                this.setPlayerSrcAndCover()
            }

        },
        // audio的pause事件
        durationConvert(time, step = 1000) {
            var duration = time / step
            var mm = parseInt(duration / 60);
            var ss = parseInt(duration % 60)
            return ((Array(2).join('0') + mm).slice(-2)) + ':' + ((Array(2).join("0") + ss).slice(-2));
        },
        artistsName(artists) {
            var names = []
            artists.forEach(element => {
                names.push(element.name);
            });
            return names.join("/")
        },
        nextSong() {
            this.currentIndex++;
            if (this.currentIndex < this.musicList.length) {
                this.setPlayerSrcAndCover()
            } else {
                this.currentIndex = 0;
                this.setPlayerSrcAndCover()
            }
        },
        preSong() {
            if (this.currentIndex > 0) {
                this.currentIndex--;
                this.setPlayerSrcAndCover()
            } else {
                this.currentIndex = this.musicList.length - 1;
                this.setPlayerSrcAndCover()
            }
        },
        displayAlbum() {
            this.isAlbumDisplay = !this.isAlbumDisplay;
        },
        onPlay() {
            this.totalTime = this.$refs.myAudio.duration;
            this.currentTime = this.$refs.myAudio.currentTime;
            var _this = this
            this.timer = setInterval(function () {
                _this.currentTime = _this.$refs.myAudio.currentTime;
                _this.$refs.musicProgress.style.width = (_this.currentTime / _this.totalTime) * 100 + "%"
            }, 1)
        },
        onPause() {
            clearInterval(this.timer)
        }
    },
});

//获得边界盒子元素，用于获取边界
function getRangeBox(_this) {
    return _this.parentElement.parentElement;

}

function inRange(event, rangeBox) {
    let rect = rangeBox.getBoundingClientRect();
    var min = rect.top;
    var max = min + rangeBox.offsetHeight;
    var clientY;
    if (event instanceof TouchEvent)
        clientY = event.touches[0].clientY;
    else
        clientY = event.clientY;

    return !(clientY < min || clientY > max);

}

function getCoefficient(event, slider) {

    let rect = slider.getBoundingClientRect();
    let K;
    let height = slider.clientHeight;
    var clientY;
    if (event instanceof TouchEvent)
        clientY = event.touches[0].clientY;
    else
        clientY = event.clientY;

    var offsetY = clientY - rect.top;
    K = 1 - offsetY / height;
    return K;
}


var volumePin = document.querySelector("#volume-pin");
var progress = document.querySelector(".progress")

volumePin.onmousedown = function () {
    var slider = getRangeBox(this);
    document.onmousemove = function (event) {
        if (inRange(event, slider)) {
            var volume = Math.round(getCoefficient(event, slider) * 100)
            progress.style.height = volume + '%';
            document.querySelector('#myAudio').volume = volume / 100
            vue.volume = volume;
        }
    }
    //防止选择内容--当拖动鼠标过快时候，弹起鼠标，bar也会移动，修复bug
    window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
}
document.onmouseup = function () {
    document.onmousemove = null
}

function changeVolume(slider) {
    //console.log("用户手指在移动")
    if (inRange(event, slider)) {
        var volume = Math.round(getCoefficient(event, slider) * 100)
        progress.style.height = volume + '%';
        document.querySelector('#myAudio').volume = volume / 100
        vue.volume = volume;
    }
}
//适配移动端
volumePin.addEventListener("touchmove", function (e) {
    var slider = getRangeBox(this);
    document.addEventListener("touchmove", changeVolume(slider), false);
    //防止选择内容
    e.preventDefault();
    window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
}, false)
document.addEventListener("touchend", function () {
    document.removeEventListener("touchmove", changeVolume)
    //console.log("触摸结束")
})


/*window.onload = function () {

    var myAudio = document.getElementById("myAudio");

    myAudio.onplay = function () {
        //part1: 画布
        var canvas = document.getElementById("canvas");
        var context = canvas.getContext("2d");

        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        var WIDTH = canvas.width;
        var HEIGHT = canvas.height;

        //part2: 音频
        var files = this.files;//声音文件
        audio.src = URL.createObjectURL(files[0]);
        audio.load();

        //part3: 分析器
        var AudCtx = new AudioContext();//音频内容
        var src = AudCtx.createMediaElementSource(audio);
        var analyser = AudCtx.createAnalyser();

        src.connect(analyser);
        analyser.connect(AudCtx.destination);
        analyser.fftSize = 128;//快速傅里叶变换, 必须为2的N次方

        var bufferLength = analyser.frequencyBinCount;// = fftSize * 0.5

        //part4: 变量
        var barWidth = (WIDTH / bufferLength) - 1;//间隔1px
        var barHeight;

        var dataArray = new Uint8Array(bufferLength);//8位无符号定长数组

        //part5: 动态监听
        function renderFrame() {
            requestAnimationFrame(renderFrame);//方法renderFrame托管到定时器，无限循环调度，频率<16.6ms/次

            context.fillStyle = "#000";//黑色背景
            context.fillRect(0, 0, WIDTH, HEIGHT);//画布拓展全屏,动态调整

            analyser.getByteFrequencyData(dataArray);//获取当前时刻的音频数据

            //part6: 绘画声压条
            var x = 0;
            for (var i = 0; i < bufferLength; i++) {
                var data = dataArray[i];//int,0~255

                var percentV = data / 255;//纵向比例
                var percentH = i / bufferLength;//横向比例

                barHeight = HEIGHT * percentV;

                //gbk,0~255
                var r = 255 * percentV;//值越大越红
                var g = 255 * percentH;//越靠右越绿
                var b = 50;

                context.fillStyle = "rgb(" + r + "," + g + "," + b + ")";
                context.fillRect(x, HEIGHT - barHeight, barWidth, barHeight);

                x += barWidth + 1;//间隔1px
            }
        }

        renderFrame();

        //part7: 播放声音
        audio.play();
    };
};*/
